// This Pine Script® code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © julzen2

//@version=5
indicator("Anchored VWAP with Deviation Bands", overlay=true)

show_custom = input.bool(true, "Show Custom")
startfrom = input.time(timestamp("01 Jan 2020 00:00 +0000"), "Start From")
deviation_band_1 = input.float(1.0, "Deviation Band 1")

// Anchored region
var float cum_vp = na
var float cum_vol = na

// Reset at the anchor point
if (na(cum_vol))
    cum_vp := 0.0
    cum_vol := 0.0

is_after_start = time >= startfrom

vp = volume * hlc3

cum_vp := is_after_start ? cum_vp + vp : na
cum_vol := is_after_start ? cum_vol + volume : na

anchored_vwap = is_after_start and cum_vol != 0 ? cum_vp / cum_vol : na

// Store historical VWAP for deviation calculation
var float[] vwap_series = array.new_float()

if is_after_start
    array.unshift(vwap_series, anchored_vwap)
    if array.size(vwap_series) > bar_index
        array.pop(vwap_series)

// Calculate standard deviation from the anchored point
var float std_dev = na
if is_after_start and array.size(vwap_series) > 1
    float mean = anchored_vwap
    float sum_sq_diff = 0.0
    for i = 0 to array.size(vwap_series) - 1
        float val = array.get(vwap_series, i)
        sum_sq_diff += math.pow(val - mean, 2)
    std_dev := math.sqrt(sum_sq_diff / array.size(vwap_series))

upper_band = show_custom and not na(anchored_vwap) ? anchored_vwap + deviation_band_1 * std_dev : na
lower_band = show_custom and not na(anchored_vwap) ? anchored_vwap - deviation_band_1 * std_dev : na

plot(upper_band, color=color.red, title="Upper Band")
plot(lower_band, color=color.red, title="Lower Band")
plot(show_custom ? anchored_vwap : na, color=color.green, title="Anchored VWAP")
